package com.meixiang.activity.account.managers.myPurse;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lzy.okhttputils.model.HttpParams;
import com.meixiang.R;
import com.meixiang.adapter.myPurse.BalanceIncomeRecordAdapter;
import com.meixiang.entity.account.CashLogIndexInfos;
import com.meixiang.global.Config;
import com.meixiang.global.GlobalType;
import com.meixiang.http.HttpCallBack;
import com.meixiang.http.HttpUtils;
import com.meixiang.main.BaseActivity;
import com.meixiang.recyclerview.OnItemClick;
import com.meixiang.tool.Tool;
import com.meixiang.util.AbStrUtil;
import com.meixiang.view.TitleView;
import com.meixiang.view.swipetoloadlayout.base.OnLoadMoreListener;
import com.meixiang.view.swipetoloadlayout.base.OnRefreshListener;
import com.meixiang.view.swipetoloadlayout.base.SwipeToLoadLayout;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * 收支记录
 *
 * @author zys
 */
public class BalanceIncomeRecordActivity extends BaseActivity {


    @Bind(R.id.title)
    TitleView title;
    BalanceIncomeRecordAdapter mAdapter;
    @Bind(R.id.swipe_target)
    RecyclerView mRecycler;
    @Bind(R.id.refresh)
    SwipeToLoadLayout swipeRefresh;
    private List<CashLogIndexInfos> incomeList = new ArrayList<CashLogIndexInfos>();
    private int pageNo = 1, pageSize = 10,totalPage=0;
    private boolean isRefresh = true;
    private DetailBroadCast broadCast;
    List<CashLogIndexInfos> infos;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_balance_income_record);
        ButterKnife.bind(this);
        super.onCreate(savedInstanceState);
        registerBroadCast();
        setEvent();

    }

    @Override
    protected void initTitle() {
        title.setTitle("收支明细");
        title.setLeftImageButton(R.mipmap.back);
        title.showLeftButton(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }
    private void registerBroadCast(){
        broadCast=new DetailBroadCast();
        IntentFilter intentFilter=new IntentFilter(GlobalType.ORDER_DETAIL_OPERATION);
        registerReceiver(broadCast,intentFilter);
    }

    @Override
    protected void initView() {
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecycler.setLayoutManager(linearLayoutManager);
        mAdapter = new BalanceIncomeRecordAdapter(this);
        mRecycler.setAdapter(mAdapter);
        mAdapter.setOnItemClickListener(new OnItemClick() {
            @Override
            public void onItemClick(View view, int position) {
                Intent intent = new Intent(BalanceIncomeRecordActivity.this,
                        IncomeDetailsActivity.class);
                intent.putExtra("pdrId",incomeList.get(position).getPdrId());
                intent.putExtra("pdrSn",incomeList.get(position).getPdrSn());
                startActivity(intent);

            }
        });

    }

    @Override
    protected void setData() {
        getData();
    }
    /**
     * orderState 	String 	必填 	10 		:订单状态 //10:待付款;/ 30:待收货;/ 40:待评价/交易完成
     * pageSize 	String 	必填 	10 	10 	每页大小
     * pageNo
     */
    public void getData() {
        incomeList.clear();
        if(isRefresh==true){
            status.showLoading();
        }
        String url;
        url = Config.CASHLOGINDEX_URL;
        HttpParams params = new HttpParams();
        params.put("pageNo",pageNo + "");
        HttpUtils.post(url, params, new HttpCallBack(this) {
            @Override
            public void onSucceed(JSONObject result, String code, String message) {
                status.removeView();
                onCompleteRefresh();
                if(result!=null){
                    totalPage=result.optInt("totalPage");
                    try {
                        infos=new Gson().fromJson(result.getString("list"),new TypeToken<List<CashLogIndexInfos>>(){}.getType());
                        incomeList.addAll(infos);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    if(totalPage==0){
                        status.showNoData("您还没有相关的记录");
                    }
                    if(!AbStrUtil.isEmpty(incomeList.toString())){
                        if(isRefresh==true){
                            mAdapter.clear();
                        }
                        mAdapter.addAll(incomeList);
                    }
                }else{
                    status.showNoData("您还没有相关的记录");


                }

            }

            @Override
            public void onError(String code, String message) {
                status.removeView();
                onCompleteRefresh();
                Tool.showTextToast(context, message);
                status.showNoNewWork(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        swipeRefresh.setRefreshing(true);
                    }
                });

            }
        });
    }


    private void onCompleteRefresh() {
        if (swipeRefresh != null) {
            if (isRefresh == true) {
                swipeRefresh.setRefreshing(false);
            } else {
                swipeRefresh.setLoadingMore(false);
            }
        }
    }

    private void setEvent() {
        swipeRefresh.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                isRefresh=false;
                pageNo++;
                if(pageNo>totalPage){
                    swipeRefresh.setLoadingMore(false);
                    return;
                }
                getData();

            }
        });
        swipeRefresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh() {
                isRefresh=true;
                pageNo = 1;
                getData();
            }
        });
    }




    @Override
    public void onClick(View v) {

    }
    private class DetailBroadCast extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
//            String orderId = intent.getStringExtra("orderId");
            swipeRefresh.setRefreshing(true);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ButterKnife.unbind(this);
        unregisterReceiver(broadCast);
    }
}
